package stark.app.function.screenshot;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.stark.screenshot.PqMode;
import com.stark.screenshot.ResolutionMode;
import com.stark.screenshot.ScreenRecCmd;
import com.stark.screenshot.ScreenRecordService;
import com.stark.screenshot.ScreenRecordState;
import com.stark.screenshot.ScreenRecorder;
import com.stark.screenshot.ScreenShotEntry;
import com.stark.screenshot.SettingManager;

import java.io.File;
import java.io.FileFilter;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.app.R;
import stark.app.databinding.FragmentScreenRecDemoBinding;
import stark.app.frame.player.VideoPlayerActivity;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

/**
 * Author：daizhongbin on 2021/7/8
 * Email：1027154338@qq.com
 * Desc:
 */
public class ScreenRecDemoFragment extends BaseNoModelFragment<FragmentScreenRecDemoBinding> {

    private ScreenRecorder mScreenRecorder = ScreenRecorder.getInstance();
    private ScreenRecAdapter mRecAdapter;
    private Handler mHander = new Handler();
    private Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            long duration = mScreenRecorder.getRecDuration();
            String strTime = TimeUtil.getHHmmss(duration);
            mDataBinding.tvTime.setText(strTime);
            mHander.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.fragment_screen_rec_demo;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {
        //这里配置点击通知栏要进入的activity
        ScreenShotEntry.sNotifyEnterActivityClass = getActivity().getClass();

        mScreenRecorder.addStateListener(mStateListener);
        mStateListener.onStateChanged(mScreenRecorder.getRecordState());

        mDataBinding.btnStartStopRec.setOnClickListener(v -> {
            if (FastClickUtil.isFastClick()) return;
            ScreenRecordState state = mScreenRecorder.getRecordState();
            if (state == ScreenRecordState.IDLE) {
                ScreenShotEntry.screenRecStartRecord(ScreenRecordService.class);
            } else {
                ScreenShotEntry.screenRecExcCmd(ScreenRecordService.class, ScreenRecCmd.STOP_REC);
            }
        });
        mDataBinding.btnPauseResumeRec.setOnClickListener(v -> {
            if (FastClickUtil.isFastClick()) return;
            ScreenRecordState state = mScreenRecorder.getRecordState();
            if (state == ScreenRecordState.RECORDING) {
                ScreenShotEntry.screenRecExcCmd(ScreenRecordService.class, ScreenRecCmd.PAUSE_REC);
            } else if (state == ScreenRecordState.PAUSE) {
                ScreenShotEntry.screenRecExcCmd(ScreenRecordService.class, ScreenRecCmd.RESUME_REC);
            }
        });

        //cbMute
        mDataBinding.cbMute.setChecked(SettingManager.getRecMute());
        mDataBinding.cbMute.setOnTouchListener((View.OnTouchListener) (v, event) -> {
            ScreenRecordState recState = mScreenRecorder.getRecordState();
            if (recState != ScreenRecordState.IDLE) {
                ToastUtils.showShort("录制过程中不能切换");
                return true;
            }
            return false;
        });
        mDataBinding.cbMute.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SettingManager.setRecMute(isChecked);
            }
        });
        //cbLandscape
        mDataBinding.cbLandscape.setChecked(SettingManager.getIsLandscape());
        mDataBinding.cbLandscape.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SettingManager.setIsLandscape(isChecked);
            }
        });
        //cbShowFloat
        mDataBinding.cbShowFloat.setChecked(false);
        mDataBinding.cbShowFloat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ScreenShotEntry.screenRecShowFloatOrNot(ScreenRecordService.class, isChecked);
            }
        });

        //rgPicMode
        mDataBinding.rgPicMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                boolean showCustom = false;
                if (checkedId == R.id.rbFhd) {
                    SettingManager.setPqMode(PqMode.FHD);
                } else if (checkedId == R.id.rbHd) {
                    SettingManager.setPqMode(PqMode.HD);
                } else if (checkedId == R.id.rbSd) {
                    SettingManager.setPqMode(PqMode.SD);
                } else if (checkedId == R.id.rbCustom) {
                    SettingManager.setPqMode(PqMode.CUSTOM);
                    showCustom = true;
                }
                mDataBinding.llCustom.setVisibility(showCustom ? View.VISIBLE : View.GONE);
            }
        });
        PqMode pqMode = SettingManager.getPqMode();
        switch (pqMode) {
            case FHD:
                mDataBinding.rgPicMode.check(R.id.rbFhd);
                break;
            case HD:
                mDataBinding.rgPicMode.check(R.id.rbHd);
                break;
            case SD:
                mDataBinding.rgPicMode.check(R.id.rbSd);
                break;
            case CUSTOM:
                mDataBinding.rgPicMode.check(R.id.rbCustom);
                break;
        }
        //分辨率
        mDataBinding.rgRes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb480p) {
                    SettingManager.setResolutionMode(ResolutionMode.RES_480P);
                } else if (checkedId == R.id.rb720p) {
                    SettingManager.setResolutionMode(ResolutionMode.RES_720P);
                } else if (checkedId == R.id.rb1080p) {
                    SettingManager.setResolutionMode(ResolutionMode.RES_1080P);
                } else if (checkedId == R.id.rb2k) {
                    SettingManager.setResolutionMode(ResolutionMode.RES_2K);
                }
            }
        });
        ResolutionMode resMode = SettingManager.getResolutionMode();
        switch (resMode) {
            case RES_480P:
                mDataBinding.rgRes.check(R.id.rb480p);
                break;
            case RES_720P:
                mDataBinding.rgRes.check(R.id.rb720p);
                break;
            case RES_1080P:
                mDataBinding.rgRes.check(R.id.rb1080p);
                break;
            case RES_2K:
                mDataBinding.rgRes.check(R.id.rb2k);
                break;
        }
        //bitrate 码率
        mDataBinding.rgBitrate.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb2mb) {
                    SettingManager.setBitrate(2 * 1024 * 1024);
                } else if (checkedId == R.id.rb4mb) {
                    SettingManager.setBitrate(4 * 1024 * 1024);
                } else if (checkedId == R.id.rb6mb) {
                    SettingManager.setBitrate(6 * 1024 * 1024);
                } else if (checkedId == R.id.rb8mb) {
                    SettingManager.setBitrate(8 * 1024 * 1024);
                }
            }
        });
        int bitrate = SettingManager.getBitrate();
        if (bitrate == 2 * 1024 * 1024) {
            mDataBinding.rgBitrate.check(R.id.rb2mb);
        } else if (bitrate == 4 * 1024 * 1024) {
            mDataBinding.rgBitrate.check(R.id.rb4mb);
        } else if (bitrate == 6 * 1024 * 1024) {
            mDataBinding.rgBitrate.check(R.id.rb6mb);
        } else if (bitrate == 8 * 1024 * 1024) {
            mDataBinding.rgBitrate.check(R.id.rb8mb);
        }
        //frame rate 帧率
        mDataBinding.rgFrameRate.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb20fps) {
                    SettingManager.setFrameRate(20);
                } else if (checkedId == R.id.rb30fps) {
                    SettingManager.setFrameRate(30);
                } else if (checkedId == R.id.rb40fps) {
                    SettingManager.setFrameRate(40);
                } else if (checkedId == R.id.rb50fps) {
                    SettingManager.setFrameRate(50);
                }
            }
        });
        int fRate = SettingManager.getFrameRate();
        if (fRate == 20) {
            mDataBinding.rgFrameRate.check(R.id.rb20fps);
        } else if (fRate == 30) {
            mDataBinding.rgFrameRate.check(R.id.rb30fps);
        } else if (fRate == 40) {
            mDataBinding.rgFrameRate.check(R.id.rb40fps);
        } else if (fRate == 50) {
            mDataBinding.rgFrameRate.check(R.id.rb50fps);
        }

        //rv
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataBinding.rvRecords.setLayoutManager(layoutManager);
        ScreenRecAdapter recAdapter = new ScreenRecAdapter();
        mRecAdapter = recAdapter;
        recAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                VideoPlayerActivity.play(getContext(), recAdapter.getItem(position).getAbsolutePath());
            }
        });
        mDataBinding.rvRecords.setAdapter(recAdapter);
    }

    @Override
    protected void initData() {
        RxUtil.create(new RxUtil.Callback<List<File>>() {
            @Override
            public void doBackground(ObservableEmitter<List<File>> emitter) {
                emitter.onNext(loadScreenRecords());
            }

            @Override
            public void accept(List<File> fileList) {
                if (fileList == null || fileList.size() == 0) {
                    mDataBinding.tvNoData.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.tvNoData.setVisibility(View.GONE);
                    mRecAdapter.setNewInstance(fileList);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mScreenRecorder.delStateListener(mStateListener);
    }

    private List<File> loadScreenRecords() {
        String recFolder = ScreenRecorder.getRecFolder();
        List<File> fileList = FileUtils.listFilesInDirWithFilter(recFolder, new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if (mScreenRecorder.getRecordState() != ScreenRecordState.IDLE) {
                    //有正在录制的文件，则要将当前正在录制的文件过滤掉
                    String recFilePath = mScreenRecorder.getRecFilePath();
                    if (recFilePath != null && recFilePath.equals(pathname.getAbsolutePath())) {
                        return false;
                    }
                }
                return true;
            }
        });
        return fileList;
    }

    private ScreenRecorder.IStateListener mStateListener = new ScreenRecorder.IStateListener() {
        @Override
        public void onStateChanged(ScreenRecordState state) {
            if (state == ScreenRecordState.RECORDING) {
                //录制中
                mHander.post(mTaskUpdateTime);
                mDataBinding.btnStartStopRec.setText("停止录制");
                mDataBinding.btnPauseResumeRec.setText("暂停录制");
                mDataBinding.btnPauseResumeRec.setVisibility(View.VISIBLE);
            } else if (state == ScreenRecordState.PAUSE) {
                //录制暂停
                mHander.removeCallbacks(mTaskUpdateTime);
                mDataBinding.btnStartStopRec.setText("停止录制");
                mDataBinding.btnPauseResumeRec.setText("恢复录制");
                mDataBinding.btnPauseResumeRec.setVisibility(View.VISIBLE);
            } else {
                //录制结束
                mHander.removeCallbacks(mTaskUpdateTime);
                mDataBinding.btnStartStopRec.setText("开始录制");
                mDataBinding.btnPauseResumeRec.setVisibility(View.GONE);
                String filePath = mScreenRecorder.getRecFilePath();
                if (TextUtils.isEmpty(filePath)) {
                    return;
                }
                if (mRecAdapter != null) {
                    try {
                        mRecAdapter.addData(new File(filePath));
                        mDataBinding.tvNoData.setVisibility(View.GONE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
}
